<template>
	<!-- 下拉框 v-bind="$attrs" 小程序不支持-->
	<uni-data-select v-if="type === 'select'" ref="select" v-model="value" v-bind="$attrs" :clear="false" :localdata="list"
	@change="onChange"></uni-data-select>
	<!-- 单选框 -->
	<uni-data-checkbox v-else-if="type === 'radio'" v-bind="$attrs" :localdata="list"></uni-data-checkbox>
</template>
<script>
	import useDictStore from '@/store/dict.js'
	export default {
		name: "dict-select",
		// 子组件不继承本组件覆盖的属性：重写change事件
		inheritAttrs: false,
		props: {
			modelValue: {
				type: [String, Number],
				default: ''
			},
			localdata: {
				type: Array,
				default () {
					return []
				}
			},
			// 字典类型
			dictType: String,
			type: {
				type: String,
				default: 'select'
			},
			// 不限
			unlimitValue: {
				type: Boolean,
				default: false
			},
			// 需要的值
			include: {
				type: Array,
				default: null
			},
			// 排除指定值
			exclude: {
				type: Array,
				default: null
			},
		},
		data() {
			return {
				value:'',
				list: []
			};
		},
		watch: {
			modelValue(val, old) {
				this.value = val
			},
			include(val, old) {
				this.loadData()
			},
		},
		created() {
			this.value = this.modelValue
			if (this.dictType) {
				this.loadData()
			}else if(this.localdata){
				this.list = this.localdata
			}
		},
		methods: {
			/**从缓存加载数据*/
			loadData() {
				// 自定义数据，格式：[{value:'1',text:'第一'}]
				this.$dict(this.dictType).then(res => {
					let datas = []
					if(this.unlimitValue){
						datas =[{value:null,text:'不限'}]
					}
					datas = datas.concat(res)
					this.setVal(datas)
				})
			},
			setVal(dicts){
			  // 过滤值
			  if(this.include){
			    this.list = dicts.filter(item=>this.include.indexOf(item.value) >= 0)
			  }else if(this.exclude){
			    this.list = dicts.filter(item=>this.exclude.indexOf(item.value) === -1)
			  }else{
			    this.list = dicts
			  }
			},
			onChange(e) {
				this.$emit('update:modelValue', e)
				this.$emit('change', e)
				// this.$refs.select.clearVal()
			},
			onnodeclick(node) {}
		}
	}
</script>

<style scoped>
	.el-tag+.el-tag {
		margin-left: 10px;
	}
</style>
